package com.magicrule.prj.common;

import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.apache.commons.lang3.StringUtils;

public class CommonUtils {
	
	static String  version="1.0";
	
	static char[] SEEDS_LOWER = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
			's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
	
	/**
	 * 
	 * @Title: generateAchar   
	 * @Description: TODO(生成指定个数的小写随机字母)   
	 * @param: @param num
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String generateAchar(int num) {
		Random r = new Random();
		String rStr = "";
		for(int i=0;i<num;i++){
			int n = r.nextInt(26);
			rStr += SEEDS_LOWER[n];
		}
		return rStr;
	}
	
	/**
	 * 
	 * @Title: generateStationaryChar   
	 * @Description: TODO(根据pstr生成指定的num个数字符串，自动补足或者截取)   
	 * @param: @param pstr
	 * @param: @param num
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String generateStationaryChar(String pstr,int num) {
		if(StringUtils.isNotEmpty(pstr)) {
			if(pstr.length()==num) {
				return pstr;
			}else if(pstr.length()>num) {
				return pstr.substring(0, num);
			}else {
				return pstr+generateAchar(num-pstr.length());
			}
		}else {
			return generateAchar(num);
		}
	}
	
	/**
	 * 生成一个UUID，去掉了"-"
	 * @return
	 */
	public static String randomUUID() {
		UUID uuid = UUID.randomUUID(); 
		return uuid.toString().replaceAll("-", "");
	}
	
	
	/**
	 * 将HttpServletRequest中的参数转化到对应的javaBean
	 * @param request
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T requestToBean(HttpServletRequest request , Class<T> clazz)
    {
        //创建javaBean对象    
        Object obj=null;
        try {
            obj=clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //4.注册一个日期格式转换器
        ConvertUtils.register(new DateLocaleConverter(), java.util.Date.class);
        //得到请求中的每个参数
        Enumeration<String> enu = request.getParameterNames();
        while(enu.hasMoreElements())
        {
            //获得参数名
            String name = enu.nextElement();
            //获得参数值
            String value = request.getParameter(name);
            //然后把参数拷贝到javaBean对象中
            try {
                BeanUtils.setProperty(obj, name, value);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        return (T)obj;
    }
	
	
	
	
	
}
